<?php

namespace app\api\controller\Broadcast;

use app\api\controller\Common;
use app\api\Logic\Broadcast\BroadcastLogic;
use app\api\Logic\Broadcast\BroadcastOrderLogic;
use app\api\Logic\Pay\PayLogic;
use app\api\model\BroadcastOrderModel;

/**
 * 直播课程订单接口
 */
class BroadcastOrder extends Common
{
    protected $noNeedLogin = ['*'];

    protected $broadcastLogic;
    protected $broadcastOrderLogic;
    protected $payLogic;

    public function _initialize()
    {
        parent::_initialize();
        $this->broadcastLogic = new BroadcastLogic();
        $this->broadcastOrderLogic = new BroadcastOrderLogic();
        $this->payLogic = new PayLogic();
    }

    /**
     * 支付方式
     * @return array[]
     */
    public function payTypeMap(){
        return [
            1 => ['type' => 1, 'name' => '微信支付'],
            2 => ['type' => 2, 'name' => '支付宝'],
            3 => ['type' => 3, 'name' => '银联支付']
        ];
    }

    /**
     * 供前端调用，返回支付方式
     */
    public function payTypeAry(){
        $list = array_values($this->payTypeMap());
        if (!empty($list)) {
            $this->success('查询成功', $list);
        }
        $this->error('暂无数据');
    }

    /**
     * 订单整理
     */
    public function collation(){
        if($this->request->isPost()){
            $param = $this->request->param();
            //验证数据
            $param = $this->verifyData($param);

            $broadcastId = $param['broadcast_id'] ?? 0;
            if(empty($broadcastId)){
                $this->error('直播课程ID必须');
            }

            //获取课程详情
            $info = $this->broadcastLogic->getInfo($param['shop_id'],$broadcastId);
            if(empty($info)){
                $this->error('课程不存在');
            }

            //验证该课程是否已支付
            $orderInfo = $this->broadcastOrderLogic->getOrderInfoByBroadcastId($param['shop_id'],$broadcastId);
            if(!empty($orderInfo)){
                if($orderInfo['status'] == 0){
                    $this->error('该课程存在未支付订单，请先支付或关闭订单后再下单');
                }else if($orderInfo['status'] == 1){
                    $this->error('该课程已支付，无需重复下单');
                }
            }

            //验证用户是否允许下单
            $checkRes = $this->broadcastOrderLogic->checkCreateOrder($broadcastId,$param['user_id']);
            if(!$checkRes){
                $this->error('该用户无法报名该课程');
            }

            if(!empty($info)){
                $this->success('查询成功',$info);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }

    /**
     * 创建订单
     */
    public function create(){
        if($this->request->isPost()){
            $param = $this->request->param();
            //验证数据
            $param = $this->verifyData($param);

            $broadcastId = $param['broadcast_id'] ?? 0;
            if(empty($broadcastId)){
                $this->error('直播课程ID必须');
            }

            if(!isset($param['pay_type']) || !isset($this->payTypeMap()[$param['pay_type']])){
                $this->error('支付方式不可用');
            }

            //获取课程详情
            $info = $this->broadcastLogic->getInfo($param['shop_id'],$broadcastId);
            if(empty($info)){
                $this->error('课程不存在');
            }

            //验证用户是否允许下单
            $checkRes = $this->broadcastOrderLogic->checkCreateOrder($broadcastId,$param['user_id']);
            if(!$checkRes){
                $this->error('用户无法报名该课程');
            }

            $orderInfo = [
                'out_trade_no' => date("YmdHis") . mt_rand(100000, 999999),
                'shop_id' => $param['shop_id'],
                'user_id' => $param['user_id'],
                'broadcast_id' => $broadcastId,
                'status' => 0,
                'price' => $info['price'] ?? 0,
                'pay_type' => $param['pay_type'],
                'createtime' => time()
            ];

            $orderId = BroadcastOrderModel::insertGetId($orderInfo);

            //创建主订单记录
            $this->payLogic->createOrder([
                'shop_id' => $param['shop_id'],
                'controller' => 'broadcast/broadcast_order',
                'order_sn' => $orderInfo['out_trade_no'],
                'order_id' => $orderId,
                'user_id' => $param['user_id'],
                'price' => $orderInfo['price'],
                'pay_type' => $param['pay_type'] == 1 ? 'wechat' : ($param['pay_type'] == 2 ? 'alipay' : ''),
                'real_price' => $orderInfo['price'],
                'pay_amount' => $orderInfo['price'],
                'status' => 0,
                'createtime' => time()
            ]);

            //如果课程价格为0，则直接支付成功
            $payStatus = 0; //待支付
            if($info['price'] == 0){
                //执行支付成功回调
                $res = $this->broadcastOrderLogic->payment(
                    [
                        'out_trade_no' => $orderInfo['out_trade_no']
                    ]
                );
                if($res){
                    $payStatus = 1; //已支付
                }
            }

            if($orderId){
                $this->success('下单成功',['order_id' => $orderId,'pay_status' => $payStatus]);
            }
            $this->error('下单失败');
        }
        $this->error('请求错误');
    }

    /**
     * 微信支付回调
     * todo 需按实际情况修改
     */
    public function notify(){
        //todo 默认写法，需按实际情况修改
        $xmlInfo = file_get_contents("php://input");
        //xms转数组
        $notifyRes = $this->xmlToArray($xmlInfo);

        //todo 回调数据验签成功
        if(true){
            $res = $this->broadcastOrderLogic->payment($notifyRes);
            if($res){
                echo 'success';
                exit;
            }
        }
        echo 'fail';
    }

    /**
     * 主订单支付回调,用于订单商品价格为0直接支付
     */
    public function pay_result(){
        $params = $this->request->param();

        $orderId = $params['order_id'] ?? 0;
        if(empty($orderId)){
            return false;
        }

        return $this->broadcastOrderLogic->payLogNotify($orderId);
    }

    /**
     * 获取订单详情
     */
    public function getInfo(){
        if($this->request->isPost()){
            $params = $this->request->param();

            //订单ID
            $orderId = $params['order_id'] ?? 0;
            if(!$orderId){
                $this->error('订单ID必须');
            }

            $info = $this->broadcastOrderLogic->getInfo($orderId);

            if(!empty($info)){
                $this->success('查询成功',$info);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }

    /**
     * 直播课程订单列表
     */
    public function orderList(){
        if($this->request->isPost()){
            $params = $this->request->param();
            //验证数据
            $params = $this->verifyData($params);

            $query = BroadcastOrderModel::where('user_id',$params['user_id'])
                ->where('status','>=',1);
            //根据学习状态筛选
            if(isset($params['study_status'])){
                $query = $query->where('study_status',$params['study_status']);
            }

            $list = $query->field('id,shop_id,user_id,broadcast_id,study_status')
                ->with([
                    'broadcastInfo' => function ($query) {
                        $query->withField('id,title,image,price,live_status');
                    }
                ])->order('createtime','desc')
                ->paginate(PAGE_SIZE);
            $list = objToArray($list) ?? [];

            if(!empty($list)){
                $this->success('查询成功',$list);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }
}
